<?php
/**
 * Core_Informant
 * 
 * @author naspeh
 * @version $Id: Informant.php 659 2008-06-15 11:34:26Z naspeh $
 */
class Core_Informant
{
    /**
     * Запускает информирование
     *
     * @param string $role_id
     * @param string $label
     * @param array $params
     * @return Core_Informant
     */
    public static function run($email, $label, array $params = array())
    {
        $params = array_merge($params, Core_Config::get('informant|params'));
        
        $letter = self::_build($label, $params);
        $letter['recipient'] = $email;
        $letter['sender'] = $params['admin'];
        self::send($letter);
    }
    /**
     * Строит сообщение
     *
     * @param string $label
     * @param array $params
     * @return string
     */
    protected static function _build($label, array $params)
    {
        $tableTemplates = new Core_Table_Templates();
        $message = $tableTemplates->fetchRow(array('label = ?' => $label))->toArray();
        foreach ($message as $key => &$part) {
            if (in_array($key, array('html', 'subject')) && preg_match_all('/%(\w+)%/i', $part, $matches)) {
                foreach ($matches[1] as $pattern) {
                    if (isset($params[$pattern])) {
                    	$part = str_ireplace('%' . $pattern . '%', $params[$pattern], $part);
                    }
                }
            }
        }
        return $message;
    }
    /**
     * Отправляет письмо на email
     *
     * @param array $letter
     * @return Core_Informant
     */
    protected static function send(array $letter)
    {
        if (!isset($letter['text'])) {
            $letter['text'] = html_entity_decode($letter['html']);
        }
        
        $mail = new Zend_Mail('utf-8');
        $mail->setSubject($letter['subject']);        
        $mail->setBodyText($letter['text']);
        $mail->setBodyHtml($letter['html'], 'utf-8');
        $mail->setFrom($letter['sender']['email'], $letter['sender']['name']);
        $mail->addTo($letter['recipient']);
        $mail->send();
    }
}